package com.flainsky.nirvanaplayer;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.videolan.vlc.android.VideoPlayerActivity;


import com.flainsky.nirvanaplayer.adpters.RankingAdapter;
import com.flainsky.nirvanaplayer.cache.ImageCache;
import com.flainsky.nirvanaplayer.globe.CheckDevice;
import com.flainsky.nirvanaplayer.globe.DataCollection;
import com.flainsky.nirvanaplayer.globe.DownloadUtils;
import com.flainsky.nirvanaplayer.globe.HistroyController;
import com.flainsky.nirvanaplayer.globe.PlayController;
import com.flainsky.nirvanaplayer.globe.ToastMaker;
import com.flainsky.nirvanaplayer.globe.DownloadUtils.DataType;
import com.flainsky.nirvanaplayer.globe.Env;
import com.flainsky.nirvanaplayer.globe.GlobeCache;
import com.flainsky.nirvanaplayer.lib.objects.Movie;
import com.flainsky.nirvanaplayer.views.MovieInfoRelativeLayout;
import com.flainsky.nirvanaplayer.webservice.FlaParameter;
import com.flainsky.nirvanaplayer.webservice.FlaWebservice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.ActionBar.LayoutParams;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */	
	private final static int MAX_OF_TOP_MOVIE = 8;
	TextView tv_main;
	TextView tv_live;
	TextView tv_movie;
	TextView tv_tv;
	TextView tv_show;
	TextView tv_news;
	ImageView hotplayIv;
	
	LinearLayout commendLayout;
	
	Button bt_setting;
	Button bt_history;
	
	TextView[] tv_selected;
	//ListView lv_ranking;
	//MovieInfoRelativeLayout[] movieInfo;
	
	ImageView largeImage;		//超大图
	ImageView trBgImage;		//右上背景图
	ImageView[] circleImage;	//8个圆圈
	
	TextView tv_hot_title;
	TextView tv_hot_info;
	
	ProgressDialog pdialog;	//进度条
	
	//singletons
	DataCollection datas;	//数据单例
	FlaWebservice ws;		//服务单例
	Env env;				//环境变量单例
	PlayController playController;	//播放控制器
	float x;
	
	Timer timer; 
	
	LoadInfoAsyncTask loadingTask;	
	RankingAdapter rAdapter;
	
	boolean loadCache = false;
	
	int numDImages = 0;
	int largeImageNo = 0;
	String hotPlayUrl = "";
	Movie hotMovie;
	ImageCache cache;
	
	enum DownloadItemOder{
		first,last,other,large
	}
	
	public static enum CommendType{
		live,movie,tv,show,news
	}
	
	public static int getTypeByCommenType(CommendType type)
	{
		if(type == CommendType.movie)
		{
			return 0;
		}
		else if(type == CommendType.live)
		{
			return 1;
		}
		else if(type == CommendType.show)
		{
			return 2;
		}
		else if(type == CommendType.tv)
		{
			return 3;
		}
		else if(type == CommendType.news)
		{
			return 4;
		}
		return 5;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
      
        //Log.v("cache", "create mainactivity");
        
        findViews();
        addListeners();
        init();        
        if(checkDevice())	//有网络连接时，从WebService读取数据
        {
        	loadingDatas();
        }
        
    }
    
    @Override
	public void onResume()
    {
    	super.onResume();    	
    	if(timer == null)
    	{
    		TimerTask task = new TimerTask(){    
    			@Override
    	        public void run() {  
    	            Message message = new Message();      
    	            message.what = 1;      
    	            handler.sendMessage(message);    
    	        }            
    	    };  
    		timer = new Timer();
    		timer.schedule(task, 3000,3000);
    	}
/*    	if(loadCache)
    	{
    		loadCache = false;
    		LoadCacheAsyncTask loadCacheTask = new LoadCacheAsyncTask();
    		loadCacheTask.execute();
    	}*/
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	if(timer!=null)
    	{
    		timer.cancel();
    		timer = null;
    	}
/*    	cache.clear();
    	loadCache = true;*/
    }
    
    @Override
    public void onDestroy()
    {
    	HistroyController.getInstance().save();
    	pdialog.dismiss();
    	//Log.v("cache", "destroy mainactivity");
    	super.onDestroy();
    }
    
    private void loadingDatas()
    {
    	loadingTask = new LoadInfoAsyncTask();
    	loadingTask.execute();
    }
    
    private boolean checkDevice()
    {
    	return CheckDevice.checkNetWorkStatus(MainActivity.this);
    	//检查广域网连接
    	/*String url = this.getString(R.string.test_connect);
    	CheckDevice.checkURL(MainActivity.this,url);*/
    }
    
    private void init()
    {
    	//启用android main thread webservice
    	//不过我给写到Task里了，这里单纯方便以后人开发
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    	.detectDiskReads()
    	.detectDiskWrites()
    	.detectNetwork()   // or .detectAll() for all detectable problems
    	.penaltyLog()
    	.build());
    	StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    	.detectLeakedSqlLiteObjects()
    	.detectLeakedClosableObjects()
    	.penaltyLog()
    	.penaltyDeath()
    	.build());

    	PlayController.makeInstance(MainActivity.this);
    	Env.makeInstance(MainActivity.this);
    	FlaWebservice.makeInstance(MainActivity.this);
    	DataCollection.makeInstance(MainActivity.this);
    	GlobeCache.makeInstance(MainActivity.this);
    	HistroyController.makeInstance(MainActivity.this);
    	HistroyController.getInstance().load();
    	
    	playController = PlayController.getInstance();
    	cache = GlobeCache.getInstance().getCache();
    	datas = DataCollection.getInstance();
    	ws = FlaWebservice.getInstance();
    	env = Env.getInstance();
    	
    	pdialog = new ProgressDialog(MainActivity.this);
    	pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int i) {
	        	 dialog.cancel();
	         }
	    });
    	pdialog.setTitle(R.string.wait);
        pdialog.setCancelable(true);
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        
        tv_main.setBackgroundResource(R.drawable.main_bottom_bg2);
    }
    
    private void findViews()
    {
    	hotplayIv = (ImageView)findViewById(R.id.hot_play_iv);
    	bt_setting = (Button)findViewById(R.id.setting_bt);
    	bt_history = (Button)findViewById(R.id.play_histroy_bt);
    	
    	tv_main = (TextView)findViewById(R.id.mainpage_tv);
        tv_live = (TextView)findViewById(R.id.live_tv);
        tv_movie = (TextView)findViewById(R.id.movie_tv);
        tv_tv = (TextView)findViewById(R.id.tv_tv);
        tv_show = (TextView)findViewById(R.id.show_tv);
        tv_news = (TextView)findViewById(R.id.news_tv);
        //lv_ranking = (ListView)findViewById(R.id.main_ranking_lv);
/*        movieInfo = new MovieInfoRelativeLayout[7];
        movieInfo[0] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info1);
        movieInfo[1] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info2);
        movieInfo[2] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info3);
        movieInfo[3] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info4);
        movieInfo[4] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info5);
        movieInfo[5] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info6);
        movieInfo[6] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info7);*/
        
        circleImage = new ImageView[8];
        circleImage[0] = (ImageView)findViewById(R.id.circle1);
        circleImage[1] = (ImageView)findViewById(R.id.circle2);
        circleImage[2] = (ImageView)findViewById(R.id.circle3);
        circleImage[3] = (ImageView)findViewById(R.id.circle4);
        circleImage[4] = (ImageView)findViewById(R.id.circle5);
        circleImage[5] = (ImageView)findViewById(R.id.circle6);
        circleImage[6] = (ImageView)findViewById(R.id.circle7);
        circleImage[7] = (ImageView)findViewById(R.id.circle8);
        
        largeImage = (ImageView)findViewById(R.id.main_image);
        trBgImage = (ImageView)findViewById(R.id.top_movie_bg_img);
        
        tv_hot_title = (TextView)findViewById(R.id.hot_title);
        tv_hot_info = (TextView)findViewById(R.id.hot_info);
        
        tv_selected = new TextView[5];
        tv_selected[0] = (TextView)findViewById(R.id.tv_select_live);
        tv_selected[1] = (TextView)findViewById(R.id.tv_select_movie);
        tv_selected[2] = (TextView)findViewById(R.id.tv_select_tv);
        tv_selected[3] = (TextView)findViewById(R.id.tv_select_show);
        tv_selected[4] = (TextView)findViewById(R.id.tv_select_news);
        
        commendLayout = (LinearLayout)findViewById(R.id.commend_ll);
    }
    
    private void addListeners()
    {
    	bt_history.setOnClickListener(this);
    	bt_setting.setOnClickListener(this);
    	
    	tv_main.setOnClickListener(this);
    	tv_live.setOnClickListener(this);
    	tv_movie.setOnClickListener(this);
    	tv_tv.setOnClickListener(this);
    	tv_show.setOnClickListener(this);
    	tv_news.setOnClickListener(this);
    	hotplayIv.setOnClickListener(this);
    	
    	for(int i = 0 ;i<5;i++)
    	{
    		tv_selected[i].setOnClickListener(this);
    	}
    	
    	for(int i = 0;i<MAX_OF_TOP_MOVIE;i++)
    	{
    		final int n = i;
            circleImage[n].setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				largeImageNo = n;
    				changeTopMovie(n);
    			}
    		});
    	}
    	largeImage.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction() == MotionEvent.ACTION_DOWN)
				{
					x = event.getX();
				}
				if(event.getAction() == MotionEvent.ACTION_UP)
				{
					if(event.getX()-x>100)
					{
						largeImageNo++;
						if(largeImageNo>=MAX_OF_TOP_MOVIE)
						{
							largeImageNo = 0;
						}
						changeTopMovie(largeImageNo);
					}
					else if(event.getX()-x<-100)
					{
						largeImageNo--;
						if(largeImageNo<=0)
						{
							largeImageNo = MAX_OF_TOP_MOVIE-1;
						}
						changeTopMovie(largeImageNo);
					}
				}
				return true;
			}
		});
    }
    

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.mainpage_tv:
			return;
		case R.id.live_tv:
			swichToLiveListPage();
			return;
		case R.id.movie_tv:
			switchToMovieListPage();
			return;
		case R.id.show_tv:
			switchToShowListPage();
			return;
		case R.id.tv_tv:
			switchToTvListPage();
			return;
		case R.id.news_tv:
			switchToNewsListPage();
			return;
		case R.id.tv_select_live:
			switchSelectedType(CommendType.live);
			return;
		case R.id.tv_select_movie:
			switchSelectedType(CommendType.movie);
			return;
		case R.id.tv_select_tv:
			switchSelectedType(CommendType.tv);
			return;
		case R.id.tv_select_show:
			switchSelectedType(CommendType.show);
			return;
		case R.id.tv_select_news:
			switchSelectedType(CommendType.news);
			return;
		case R.id.setting_bt:
			startSetting();
			return;
		case R.id.hot_play_iv:
			//playController.setCurrentPlayUrl(hotPlayUrl);
			playController.setCurrentPlayMovie(hotMovie);
			LoadingVideoAsyncTask loadingVideo = new LoadingVideoAsyncTask();
			loadingVideo.execute();
			return;
		case R.id.play_histroy_bt:
			startHistory();
			return;
		}
	}
	
	private void play()
	{
		Intent intent = new Intent(this,VideoPlayerActivity.class);
		startActivity(intent);
	}
	
/*	private void play(String url)
	{
		playController.setCurrentPlayUrl(url);
		Intent intent = new Intent(this,VideoPlayerActivity.class);
		startActivity(intent);
	}*/
	
	private void startSetting()
	{
		Intent intent = new Intent(MainActivity.this,ConfigerActivity.class);
		startActivity(intent);
	}
	
	private void startHistory()
	{
		Intent intent = new Intent(MainActivity.this,HistoryActivity.class);
		startActivity(intent);
	}
	
	private void switchToNewsListPage()
	{
		Intent intent = new Intent(MainActivity.this,NewsListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void switchToTvListPage()
	{
		Intent intent = new Intent(MainActivity.this,TvListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void switchToShowListPage()
	{
		Intent intent = new Intent(MainActivity.this,ShowListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void switchToMovieListPage()
	{
		Intent intent = new Intent(MainActivity.this,MovieListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void swichToLiveListPage()
	{
		Intent intent = new Intent(MainActivity.this,LiveListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void fillData()
	{
		//填充排行榜
		//rAdapter = new RankingAdapter(MainActivity.this, datas.getHotList());
		//lv_ranking.setAdapter(rAdapter);
		
		//下载数据，今日推荐下载小图，上面下载大小图
		//downloadImages();
		
		//填充今日推荐
		refreshTodayCommend(CommendType.live);
		
		//填充上面，并启动循环线程
		largeImageNo = 0;
		changeTopMovie(0);
		loadCache = true;
	}
	
	//数据加载cache
	public class LoadCacheAsyncTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute()
		{
			pdialog.setMessage(MainActivity.this.getString(R.string.load_data));
	        pdialog.show();
		}
		@Override
		protected Void doInBackground(Void... arg0) {
			//加载大图
			BuffHotMovieImage(datas.getHotList());
			return null;
		}
		@Override
	    protected void onPostExecute(Void result) {
			pdialog.cancel();
		}
		
	}
	
	//数据加载Task
	public class LoadInfoAsyncTask extends AsyncTask<Void, Void, Void> {
		public LoadInfoAsyncTask() {
			// TODO Auto-generated constructor stub			
	        pdialog.setMessage(MainActivity.this.getString(R.string.load_data));
	        pdialog.show();
		}
		@Override
		protected void onPreExecute()
		{
			//nothing to do now....
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			//---------------在这里从WebService加载数据
			//加载电影相关
			//加载所有电影地区
			datas.setAreaList(ws.getStringList(FlaWebservice.AREA_METHOD,CommendType.movie));
			//加载所有电影年份（倒序）
			datas.setYearList(ws.getStringList(FlaWebservice.YEAR_METHOD,CommendType.movie));
			//加载所有电影种类
			datas.setCategoryList(ws.getStringList(FlaWebservice.CATEGORY_METHOD,CommendType.movie));
			
			//加载今日推荐电影列表
			List<FlaParameter> paras = new ArrayList<FlaParameter>();
			paras.add(new FlaParameter("count",String.valueOf(10)));
			datas.setTodayList(ws.getMovieList(FlaWebservice.MOVIE_NEWS_METHOD, paras));
			
			//加载首页上侧推荐最热列表
			List<FlaParameter> paras2 = new ArrayList<FlaParameter>();
			paras2.add(new FlaParameter("count",String.valueOf(8)));
			datas.setLivePopularList(ws.getMovieList(FlaWebservice.LIVE_POPULAR_METHOD, paras2));
			
			datas.setMoviePopularList(ws.getMovieList(FlaWebservice.MOVIE_POPULAR_METHOD, paras2));
			
			List<FlaParameter> paras22 = new ArrayList<FlaParameter>();
			paras22.add(new FlaParameter("count",String.valueOf(8)));
			paras22.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.tv))));
			datas.setTvPopularList(ws.getMovieList(FlaWebservice.TYPE_POPULAR_METHOD, paras22));
			
			List<FlaParameter> paras23 = new ArrayList<FlaParameter>();
			paras23.add(new FlaParameter("count",String.valueOf(8)));
			paras23.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.show))));
			datas.setShowPopularList(ws.getMovieList(FlaWebservice.TYPE_POPULAR_METHOD, paras23));
			
			List<FlaParameter> paras24 = new ArrayList<FlaParameter>();
			paras24.add(new FlaParameter("count",String.valueOf(8)));
			paras24.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.news))));
			datas.setNewsPopularList(ws.getMovieList(FlaWebservice.TYPE_POPULAR_METHOD, paras24));
			
			//加载电影播放次数排名列表（界面上已删除）
			/*List<FlaParameter> paras3 = new ArrayList<FlaParameter>();
			paras3.add(new FlaParameter("count",String.valueOf(10)));
			datas.setRankingList(ws.getMovieList(FlaWebservice.MOVIE_TIMES_METHOD, paras3));*/
			
			
			//加载综艺相关-----------------------------------------
			datas.setAreaShowList(ws.getStringList(FlaWebservice.AREA_METHOD,CommendType.show));
			datas.setYearShowList(ws.getStringList(FlaWebservice.YEAR_METHOD,CommendType.show));
			datas.setCategoryShowList(ws.getStringList(FlaWebservice.CATEGORY_METHOD,CommendType.show));
			
			//加载电视剧相关-----------------------------------------
			datas.setAreaTvList(ws.getStringList(FlaWebservice.AREA_METHOD,CommendType.tv));
			datas.setYearTvList(ws.getStringList(FlaWebservice.YEAR_METHOD,CommendType.tv));
			datas.setCategoryTvList(ws.getStringList(FlaWebservice.CATEGORY_METHOD,CommendType.tv));
			
			//加载新闻相关-----------------------------------------
			datas.setAreaNewsList(ws.getStringList(FlaWebservice.AREA_METHOD,CommendType.news));
			datas.setYearNewsList(ws.getStringList(FlaWebservice.YEAR_METHOD,CommendType.news));
			datas.setCategoryNewsList(ws.getStringList(FlaWebservice.CATEGORY_METHOD,CommendType.news));
			
			//加载今日推荐直播列表
			List<FlaParameter> paras4 = new ArrayList<FlaParameter>();
			paras4.add(new FlaParameter("count",String.valueOf(10)));
			paras4.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.live))));
			datas.setTodayLiveList(ws.getMovieList(FlaWebservice.TYPE_NEWS_METHOD, paras4));
			
			List<FlaParameter> paras5 = new ArrayList<FlaParameter>();
			paras5.add(new FlaParameter("count",String.valueOf(10)));
			paras5.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.show))));
			datas.setTodayShowList(ws.getMovieList(FlaWebservice.TYPE_NEWS_METHOD, paras5));
			
			List<FlaParameter> paras6 = new ArrayList<FlaParameter>();
			paras6.add(new FlaParameter("count",String.valueOf(10)));
			paras6.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.tv))));
			datas.setTodayTvList(ws.getMovieList(FlaWebservice.TYPE_NEWS_METHOD, paras6));
			
			List<FlaParameter> paras7 = new ArrayList<FlaParameter>();
			paras7.add(new FlaParameter("count",String.valueOf(10)));
			paras7.add(new FlaParameter("type", String.valueOf(getTypeByCommenType(CommendType.news))));
			datas.setTodayNewsList(ws.getMovieList(FlaWebservice.TYPE_NEWS_METHOD, paras7));
			//加载大图
			datas.setHotList(datas.getMoviePopularList());
			BuffHotMovieImage(datas.getHotList());
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(datas.getHotList() == null || datas.getHotList().size() == 0)
			{
				ToastMaker.showToastLong(MainActivity.this, R.string.netservice_error);
			}
			
			pdialog.cancel();
			fillData();
			switchSelectedType(CommendType.movie);
		}
	}
	
	//图片下载Task
	public class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> {

		String mUrl;
		DownloadItemOder mOrder;
		ImageView mIv;
		int mId;
		boolean isFinish = false;
		boolean isNotExit = false;
		public DownloadImageAsyncTask(String url,DownloadItemOder order,ImageView iv,int id)
		{
			mUrl = url;
			mOrder = order;
			mIv = iv;
			mId = id;
		}
		@Override
		protected void onPreExecute()
		{
			//pdialog.show();
			if(mOrder == DownloadItemOder.large)
			{
				if(mId != numDImages)
				{
					isFinish = true;
				}
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if(!isFinish)
			{
				isNotExit = !DownloadUtils.downloadFile(MainActivity.this,mUrl,DownloadUtils.DataType.image);
			}
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(mIv!=null)
			{
				if(mOrder == DownloadItemOder.large)
				{
					if(mId != numDImages)
					{
						isFinish = true;
					}
				}
				if(pdialog!=null&&pdialog.isShowing())
				{
					pdialog.cancel();
				}
				if(isNotExit)
				{
					Toast.makeText(MainActivity.this, mUrl+" file not exits in server!",Toast.LENGTH_LONG).show();
					return;
				}
				if(isFinish)return;
				String str = DownloadUtils.getUrlName(mUrl);
				String path = DownloadUtils.getDataParentPath(DataType.image)+str;
				//Options op = new Options();
				Bitmap bmp = BitmapFactory.decodeFile(path);
				mIv.setImageBitmap(bmp);
				cache.put(mId, bmp);
				//Log.d("cache", ""+mId+":"+bmp.getWidth());
			}
		}
	}
	
	private void switchSelectedType(CommendType type)
	{
		if(type == CommendType.live)
		{
			datas.setHotList(datas.getLivePopularList());
		}
		else if(type == CommendType.movie)
		{
			datas.setHotList(datas.getMoviePopularList());
		}
		else if(type == CommendType.tv)
		{
			datas.setHotList(datas.getTvPopularList());
		}
		else if(type == CommendType.show)
		{
			datas.setHotList(datas.getShowPopularList());
		}
		else if(type == CommendType.news)
		{
			datas.setHotList(datas.getNewsPopularList());
		}
		refreshTodayCommend(type);
		for(int i = 0;i<5;i++)
		{
			tv_selected[i].setBackgroundDrawable(null);
			tv_selected[i].setTextColor(Color.GRAY);
		}
		if(type==CommendType.live)
		{
			tv_selected[0].setBackgroundResource(R.drawable.sort_selected_bt);
			tv_selected[0].setTextColor(Color.BLACK);
		}
		else if(type==CommendType.movie)
		{
			tv_selected[1].setBackgroundResource(R.drawable.sort_selected_bt);
			tv_selected[1].setTextColor(Color.BLACK);
		}
		else if(type==CommendType.tv)
		{
			tv_selected[2].setBackgroundResource(R.drawable.sort_selected_bt);
			tv_selected[2].setTextColor(Color.BLACK);
		}
		else if(type==CommendType.show)
		{
			tv_selected[3].setBackgroundResource(R.drawable.sort_selected_bt);
			tv_selected[3].setTextColor(Color.BLACK);
		}
		else if(type==CommendType.news)
		{
			tv_selected[4].setBackgroundResource(R.drawable.sort_selected_bt);
			tv_selected[4].setTextColor(Color.BLACK);
		}
	}
	
	private void BuffHotMovieImage(List<Movie> list)
	{
		if(list == null)return;
		for(Movie movie:list)
		{
			if(!DownloadUtils.downloadFile(MainActivity.this,movie.mBimage,DownloadUtils.DataType.image))
			{
				//Toast.makeText(MainActivity.this, movie.mBimage+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			if(!DownloadUtils.downloadFile(MainActivity.this,movie.mSimage,DownloadUtils.DataType.image))
			{
				//Toast.makeText(MainActivity.this, movie.mSimage+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			String bImage = DownloadUtils.getDataParentPath(DataType.image) + DownloadUtils.getUrlName(movie.mBimage);
			String sImage = DownloadUtils.getDataParentPath(DataType.image) + DownloadUtils.getUrlName(movie.mSimage);
			/*Options opt = new Options();
			opt.inSampleSize = 4;*/
			Bitmap bBmp = BitmapFactory.decodeFile(bImage);
			Bitmap sBmp = BitmapFactory.decodeFile(sImage);
			cache.put(movie.mId*GlobeCache.MULTIPLE_OF_SMALL, sBmp);
			cache.put(movie.mId, bBmp);
			//Log.d("cache",String.valueOf(cache.size()));
			//Log.d("cache", "put "+movie.mBimage);
		}
	}
	
	private void changeTopMovie(int position)
	{
		//int max = datas.getHotList().size()<MAX_OF_TOP_MOVIE?datas.getHotList().size():MAX_OF_TOP_MOVIE;
		if(largeImageNo>=MAX_OF_TOP_MOVIE||largeImageNo>=datas.getHotList().size())
		{
			largeImageNo = 0;
		}
		for(int i = 0;i<MAX_OF_TOP_MOVIE;i++)
		{
			circleImage[i].setImageResource(R.drawable.circle2);
		}
		circleImage[position].setImageResource(R.drawable.circle1);
		
		if(position>=datas.getHotList().size())
		{
			return;
		}
		
		Movie movie = datas.getHotList().get(position);
		hotPlayUrl = datas.getHotList().get(position).mPlay_url;
		hotMovie = datas.getHotList().get(position);
		tv_hot_title.setText(movie.mTitle);
		tv_hot_info.setText(movie.mIntro);
/*		DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.other, largeImage);
		DownloadImageAsyncTask dat2 = new DownloadImageAsyncTask(movie.mSimage, DownloadItemOder.other, trBgImage);
		dat1.execute();
		dat2.execute();*/
		if(cache.containsKey(movie.mId))
		{
			//Log.d("cache", "has large");
			Bitmap bmp = cache.get(movie.mId);
			largeImage.setImageBitmap(bmp);
			/*DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.large, largeImage,position);
			dat1.execute();*/
		}
		else
		{
			numDImages = movie.mId;
/*			Log.d("cache",String.valueOf(cache.size())+":  mid:"+movie.mId);*/
			largeImage.setImageResource(R.drawable.loading);
			DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.large, largeImage,movie.mId);
			dat1.execute();
		}
		if(cache.containsKey(movie.mId*GlobeCache.MULTIPLE_OF_SMALL))
		{
			//Log.d("cache", "has small");
			trBgImage.setImageBitmap(cache.get(movie.mId*GlobeCache.MULTIPLE_OF_SMALL));
		}
		else
		{
			trBgImage.setImageResource(R.drawable.loading);
			DownloadImageAsyncTask dat2 = new DownloadImageAsyncTask(movie.mSimage, DownloadItemOder.other, trBgImage,movie.mId*GlobeCache.MULTIPLE_OF_SMALL);
			dat2.execute();
		}
	}
	
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what)
			{
			case 1:
				if(loadCache)
				{	
					int max = datas.getHotList().size()<MAX_OF_TOP_MOVIE?datas.getHotList().size():MAX_OF_TOP_MOVIE;
					largeImageNo++;
					//Log.d("num of list",""+max);
					//Log.d("num of list","no:"+largeImageNo);
					if(largeImageNo>=max)
					{
						largeImageNo = 0;
					}
					changeTopMovie(largeImageNo);
				}
				break;
			}
		}
	};
	
	private void refreshTodayCommend(CommendType type)
	{
		commendLayout.removeAllViews();
		List<Movie> list = null;
		switch(getTypeByCommenType(type))
		{
		case 0:
			list = datas.getTodayList();
			break;
		case 1:
			list = datas.getTodayLiveList();
			break;
		case 2:
			list = datas.getTodayShowList();
			break;
		case 3:
			list = datas.getTodayTvList();
			break;
		case 4:
			list = datas.getTodayNewsList();
			break;
		}
		
		if(list == null)return;
		for(Movie movie : list)
		{
			MovieInfoRelativeLayout info = new MovieInfoRelativeLayout(MainActivity.this, null);
			int width = (int) this.getResources().getDimension(R.dimen.commend_item_width);
			int height = (int) this.getResources().getDimension(R.dimen.commend_item_height);
			int margin = (int) this.getResources().getDimension(R.dimen.commend_item_margin);
			LayoutParams lp = new LayoutParams(width+margin,height);
			info.setLayoutParams(lp);
			info.setImageResource(R.drawable.loading2);
			info.setTitle(movie.mTitle);
			info.setRb(movie.mComment);
			DownloadImageAsyncTask dit = new DownloadImageAsyncTask(movie.mSimage, DownloadItemOder.other, info.getImageView(),-1);
			dit.execute();
			final Movie movie2 = movie;
			info.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//playController.setCurrentPlayUrl(movie2.mPlay_url);
					playController.setCurrentPlayMovie(movie2);
					LoadingVideoAsyncTask loadingVideoTask = new LoadingVideoAsyncTask();
					loadingVideoTask.execute();
				}
			});
			commendLayout.addView(info);
		}
	}
	
	public class LoadingVideoAsyncTask extends AsyncTask<Void, Void, Void> {
		boolean isNotExit = false;
		public LoadingVideoAsyncTask()
		{
			pdialog.setMessage(MainActivity.this.getString(R.string.video_loading));
		}
		
		@Override
		protected void onPreExecute()
		{
			if(pdialog!=null && !pdialog.isShowing())
			{
				pdialog.show();
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			isNotExit = !DownloadUtils.downloadFile(MainActivity.this,PlayController.getInstance().getCurrentPlayUrl(), DataType.movie);
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(pdialog != null && pdialog.isShowing())
			{
				pdialog.dismiss();
			}
			if(isNotExit)
			{
				Toast.makeText(MainActivity.this, PlayController.getInstance().getCurrentPlayUrl()+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			play();
		}
	}
}